const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const formatMillisecond2Date = millsecond =>
{
  var ret = new Date();
  ret.setTime(millsecond);

  return ret;
}

//获取现在的时间戳
const getCurrentSecondTime = ()=>
{
  var currentDate = new Date();
  return currentDate.getTime()/1000;
}

const getLeftTime = second =>
{
  var day = Math.floor(second / (3600 * 24));
  var hour = Math.floor((second - day * 3600 * 24) / 3600);
  var minute = Math.floor(((second - day * 3600 * 24) - (hour * 3600)) / 60);
  var second = second % 60;

  var ret = 
  {
      day : day,
      hour : hour,
      minute : minute,
      second : second,
  }

  return ret;
}


const formatSecond2Date = second =>
{
  return formatMillisecond2Date(second * 1000);
}

//显示转圈圈提示
var showBusy = text => 
{
  var toast = function()
  {
    wx.showToast({title: text, icon:"loading", duration:3000});
  }
  var locker = setTimeout(toast, 1000)

  console.log("上锁"+locker);

  return locker;
}

//显示成功提示,成功不提示，关闭通讯中
var showSuccess = (locker, text) => 
{

  console.log("解锁"+locker);
  clearTimeout(locker);
  wx.hideToast()
}

//显示失败提示
var showModel = (title, content) =>{
  wx.hideToast();
  wx.showModal({
    title,
    content:JSON.stringify(content),
    showCancel:false
  })

}

function Name(name, len, replace)
{
  var ret = "";

  if(name.length > len)
  {
    ret = name.substring(0, len);
    ret += replace;
  }
  else
  {
    ret = name;
  }

  return ret;
}

function getLeftTimeStr (second) {
  if (second <= 0) {
    return { h: "00", m: "00", s: "00" }
  }

  var t = getLeftTime(second);
  var h = "00";
  var m = "00";
  var s = "00";
  t.hour = t.hour + t.day * 24;
  if (t.hour < 10) {
    h = "0" + t.hour;
  }
  else {
    h = t.hour;
  }

  if (t.minute < 10) {
    m = "0" + t.minute;
  }
  else {
    m = t.minute;
  }

  if (t.second < 10) {
    s = "0" + t.second;
  }
  else {
    s = t.second;
  }

  return { h: h, m: m, s: s }
}

module.exports = {
  formatTime: formatTime,
  showBusy,
  showSuccess,
  showModel,
  formatMillisecond2Date: formatMillisecond2Date,
  formatSecond2Date: formatSecond2Date,
  getLeftTime: getLeftTime,
  getCurrentSecondTime:getCurrentSecondTime,
  Name:Name,
  getLeftTimeStr: getLeftTimeStr
}
